package com.example.xiaoxueqixiangmu.Fragment;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.example.xiaoxueqixiangmu.R;
import com.example.xiaoxueqixiangmu.jiemian.ChooseTrainsActivity;
import com.example.xiaoxueqixiangmu.jiemian.HistoryAdapter;
import com.example.xiaoxueqixiangmu.jiemian.MySQLiteOpenHelper;
import com.example.xiaoxueqixiangmu.jiemian.chepiaoyudingActivity;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.logging.Handler;
import java.util.logging.SocketHandler;


public class TicketFragment extends Fragment {
    private TextView dataTextView;
    private TextView TV1,TV2 , txtHis1 , txtHis2 , th;
    private ImageView IM2;
    private Button Bt1;
    private String fromStationName , toStationName , startTrainDate;

    int myear;
    int mmonth;
    int mday;
    private static final String TAG = "TicketFragment";
    Calendar calendar=Calendar.getInstance();
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.activity_ticket, container, false);
    }

    @Override
    public void onStart() {
        super.onStart();
        dataTextView=getView().findViewById(R.id.dataTextView);
        IM2=getView().findViewById(R.id.IM2);
        TV1=getView().findViewById(R.id.TV1);
        TV2=getView().findViewById(R.id.TV2);
        Bt1=getView().findViewById(R.id.Bt1);
        th = getActivity().findViewById(R.id.th);
        txtHis1 = getActivity().findViewById(R.id.txtHis1);
        txtHis2 = getActivity().findViewById(R.id.txtHis2);
        fromStationName = TV1.getText().toString();
        toStationName = TV2.getText().toString();
        final MySQLiteOpenHelper mySQLiteOpenHelper = new MySQLiteOpenHelper(TicketFragment.this.getContext(),null,null,1);
        SQLiteDatabase readableDatabase = mySQLiteOpenHelper.getReadableDatabase();
        Cursor cursor = readableDatabase.query("history", new String[]{"goCity", "backCity"}, null, null, null, null, null, null);
        int i = 0;
        while ( cursor.moveToNext() ){
            if ( i < 2 ){
                String goCity = cursor.getString(cursor.getColumnIndex("goCity"));
                String backCity = cursor.getString(cursor.getColumnIndex("backCity"));
                switch ( i ){
                    case 0:
                        txtHis1.setText(goCity+"->"+backCity);
                        break;
                    case 1:
                        txtHis2.setText(goCity+"->"+backCity);
                        break;

                }
            }
            i++;
        }

        th.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LayoutInflater layoutInflater = LayoutInflater.from(TicketFragment.this.getContext());
                View item = layoutInflater.inflate(R.layout.listview_history, null, false);
                ListView lv = item.findViewById(R.id.lv);

                MySQLiteOpenHelper mySQLiteOpenHelper1 = new MySQLiteOpenHelper(TicketFragment.this.getContext(),null,null,1);
                SQLiteDatabase readableDatabase1 = mySQLiteOpenHelper1.getReadableDatabase();
                Cursor cu = readableDatabase1.query("history", new String[]{"goCity", "backCity"}, null, null, null, null, null, null);
                ArrayList<HashMap<String,String>> dataArray = new ArrayList<>();
                while ( cu.moveToNext() ){
                    HashMap<String,String> hashMap = new HashMap<>();
                    hashMap.put("goCity",cu.getString(cu.getColumnIndex("goCity")));
                    hashMap.put("backCity",cu.getString(cu.getColumnIndex("backCity")));
                    dataArray.add(hashMap);
                }
                HistoryAdapter historyAdapter = new HistoryAdapter(TicketFragment.this.getContext(),dataArray);
                lv.setAdapter(historyAdapter);
                AlertDialog.Builder alert = new AlertDialog.Builder(TicketFragment.this.getContext() );
                alert.setIcon(null)
                        .setTitle("查询历史记录")
                        .setView(item)
                        .setPositiveButton("确定",null)
                        .create()
                        .show();

            }
        });

        TV1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), ChooseTrainsActivity.class);
                intent.putExtra("key",100);
                startActivityForResult(intent,100);
            }
        });

        TV2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), ChooseTrainsActivity.class);
                intent.putExtra("key",101);
                startActivityForResult(intent,101);
            }
        });

     //起点和终点城市的交换按钮点击的监听事件
        IM2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 设置动画的代码
                TV2.setText("沈阳");
                TV1.setText("上海");
                Animation animation = AnimationUtils.loadAnimation(getContext(), R.anim.anim_toleft);
                Animation animation1 = AnimationUtils.loadAnimation(getContext(), R.anim.anim_toright);
                TV2.startAnimation(animation);
                TV1.startAnimation(animation1);
            }
        });


       //选择出发日期的点击事件，弹出日期表进行选择。
        dataTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myear=calendar.get(Calendar.YEAR);
                mmonth=calendar.get(Calendar.MONTH);
                mday=calendar.get(Calendar.DAY_OF_MONTH);
                // 1.
                DatePickerDialog.OnDateSetListener listener=new DatePickerDialog.OnDateSetListener(){

                            @Override
                            public void onDateSet(DatePicker view, int m_year , int m_month, int m_dayOfMonth) {
                                myear=m_year;
                                mmonth=m_month+1;
                                mday=m_dayOfMonth;
                                String today = myear+"年"+mmonth+"月"+mday+"日";
                                dataTextView.setText(today);
                                startTrainDate = myear+"-"+mmonth+"-"+mday;
                            }

                        };

                // 2.
                DatePickerDialog datePickerDialog = new DatePickerDialog(getContext(),listener,myear,mmonth,mday){
                    @Override
                    public void onDateChanged(@NonNull DatePicker view, int year, int month, int dayOfMonth) {
                        if (year < year)
                            view.updateDate(myear,mmonth,mday);
                        if (month < mmonth && year == myear)
                            view.updateDate(myear, mmonth, mday);
                        if (dayOfMonth < mday && year == myear && month == mmonth)
                            view.updateDate(myear, mmonth, mday);

                    }
                };
                datePickerDialog.setTitle("选择日期");
                datePickerDialog.setIcon(null);
                datePickerDialog.show();


            }
        });

        //Bt1  查询按钮,点击查询车次的列表，跳转到车次的界面（chepiaoyudingActivity）。
        Bt1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(getActivity(), chepiaoyudingActivity.class);
                intent.putExtra("fromStationName",fromStationName);
                intent.putExtra("toStationName",toStationName);
                intent.putExtra("startTrainDate",startTrainDate);
                intent.putExtra("myear",myear);
                intent.putExtra("mmonth",mmonth);
                intent.putExtra("mday",mday);
                intent.putExtra("goCity",TV1.getText().toString());
                intent.putExtra("backCity",TV2.getText().toString());
                SQLiteDatabase readableDatabase = mySQLiteOpenHelper.getReadableDatabase();
                ContentValues contentValues = new ContentValues();
                contentValues.put("goCity",TV1.getText().toString());
                contentValues.put("backCity",TV2.getText().toString());
                readableDatabase.insert("history",null,contentValues);

                startActivity(intent);
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        switch ( requestCode ){
            case 100:
                String city = data.getStringExtra("city");
                TV1.setText(city);
                break;
            case 101:
                String city1 = data.getStringExtra("city");
                TV2.setText(city1);
                break;
        }
    }
}
